<?php

namespace App\Http\Controllers\Component;

use App\Services\Service\UploadService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UploadController extends Controller
{
    public function uploader(Request $request)
    {
        $file = $request->file('file');
        if ($file){
            $name = explode('.',$file->getClientOriginalName());
            $extension = $file->getClientOriginalExtension();
            if (!in_array(strtolower($extension),['jpeg', 'jpg', 'bmp', 'png'])){
                return $this->_error('格式错误');
            }
            if ($file->getSize() > 8388608){
                return $this->_error('上传文件过大,请压缩过后在上传');
            }
            $dir_path = 'public/storage/images_cloud' . '/' . date('Ym');
            try{
                $image_path = \Storage::putFile($dir_path,$file);

                $path = $image_path;
                $path = explode('/',$path,2);
                $path = $path[1];
                $data = [
                    'name' => $name['0'],
                    'file_name' => $file->getClientOriginalName(),
                    'path' => $path,
                    'extension' => $file->getClientOriginalExtension(),
                    'size' => $file->getSize(),
                    'status' => '1',
                ];
                $result = UploadService::store($data);
                if ($result) {
                    return $this->_msg('上传成功',['message'=>$path]);
                } else {
                   return $this->_error('上传失败');
                }
            }catch (\Exception $exception){
                return $this->_error($exception->getMessage());
            }
        }else{
            return $this->_error('上传失败');
        }
    }
}
